<template>
  <div class="AdminNews">
    <div class="tit">
      <h1>AdminNews 列表</h1>
      <el-button @click="toCreatPage" type="primary" icon="el-icon-plus"
        >新建</el-button
      >
    </div>
    <el-table stripe border :data="newsList" style="width: 100%">
      <!--      empty-text="暂无数据"-->
      <template #empty>暂无数据</template>
      <el-table-column label="#" width="100" prop="id"> </el-table-column>
      <el-table-column label="标题" width="240" prop="title"> </el-table-column>
      <el-table-column label="描述" prop="desc" />
      <el-table-column label="创建时间" prop="create_at" />
      <el-table-column label="发布者" prop="author" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-view"
            circle
            @click="handleShow(scope.row.id)"
          />
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.row.id)"
          />
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDelete(scope.row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, next"
      :total="Infinity"
      @current-change="currentChange"
    />
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import axios from "axios";

export default {
  name: "AdminNews",
  computed: {
    ...mapState("news", ["newsList"]),
  },
  data() {
    return {
      page: 1,
      size: 2,
    };
  },
  async created() {
    await this.getList();
  },
  methods: {
    ...mapMutations("news", ["SET_NEWS_LIST"]),
    toCreatPage() {
      this.$router.push({
        name: "AdminNewsCreate",
      });
    },
    handleShow(id) {
      this.$router.push({
        name: "AdminNewsShow",
        params: {
          id,
        },
      });
    },
    handleEdit(id) {
      this.$router.push({
        name: "AdminNewsEdit",
        params: {
          id,
        },
      });
    },
    async handleDelete(id) {
      await axios({
        method: "DELETE",
        url: `http://localhost:3000/news/${id}`,
      });
      await this.getList(this.page);
    },
    async getList(page = 1) {
      try {
        const res = await axios({
          url: `http://localhost:3000/news?_limit=10&_page=${page}`,
        });
        console.log(res);
        this.SET_NEWS_LIST(res.data);
      } catch (e) {
        this.$message.error("网络错误");
      }
    },
    currentChange(page) {
      this.page = page;
      this.getList(this.page);
    },
  },
};
</script>

<style scoped lang="less">
.tit {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
